import React from 'react';
import {Menu,Checkbox,Button,Dropdown,Input,Row,Col,Upload,Modal,message} from 'antd';

import './css/AddProducts.css'
import {DownOutlined, UserOutlined,PlusOutlined,QuestionCircleOutlined} from "@ant-design/icons";
import axios from "axios";
import {withRouter} from 'react-router-dom'

const menu = (
    <Menu>
        <Menu.Item key="1">
            <UserOutlined />
            1st menu item
        </Menu.Item>
        <Menu.Item key="2">
            <UserOutlined />
            2nd menu item
        </Menu.Item>
        <Menu.Item key="3">
            <UserOutlined />
            3rd item
        </Menu.Item>
    </Menu>
);
const {TextArea} = Input

function getBase64(file) {
    return new Promise((resolve, reject) => {
        const reader = new FileReader();
        reader.readAsDataURL(file);
        reader.onload = () => resolve(reader.result);
        reader.onerror = error => reject(error);
    });
}

class AddProducts extends React.Component {
    constructor(props) {
        super(props);
    }

    state = {
        isShow:false,
        previewVisible: false,
        previewImage: '',
        previewTitle: '',
        fileList: [],
        goodsType: [],
        typeSelectValue:'',
        visible:false,
        newType:'',
        goodsName:'',
        goodsSpecifications:'',
        goodsUnit:'',
        goodsDesc:'',
        goodsMarketPrice:'',
        referenceCostPrice:'',
        goodsState:'',
        goodsUnitData:[],
        selectUnit:''
    }
    setShow(){
        this.setState({
            isShow:true
        })
    }
    setHide(){
        this.setState({
            isShow:false
        })
    }
    onChange(e){
        let state = ''
        if(e.target.checked===true){
            state = '立即上架'
        }else {
            state = '未上架'
        }
        this.setState({
            goodsState:state
        })
    }
    handleCancel = () => this.setState({ previewVisible: false });
    handlePreview = async file => {
        if (!file.url && !file.preview) {
            file.preview = await getBase64(file.originFileObj);
        }

        this.setState({
            previewImage: file.url || file.preview,
            previewVisible: true,
            previewTitle: file.name || file.url.substring(file.url.lastIndexOf('/') + 1),
        });
    };
    handleChange = ({ fileList }) => this.setState({ fileList });
    subProducts(){
        let formData = new FormData()
        let goodsUnitId = 0
        let repositoryId = 0
        let goodsUnitData = this.state.goodsUnitData
        goodsUnitData.map(item=>{
            if(item.goodsUnitName===this.state.selectUnit){
                goodsUnitId = item.key
            }
        })
        let repositoryData = this.state.goodsType
        repositoryData.map(item=>{
            if(item.goodsTypeName===this.state.typeSelectValue){
                repositoryId = item.key
            }
        })

        formData.append('goodsName',this.state.goodsName)
        formData.append('goodsType',repositoryId)
        formData.append('goodsSpecifications',this.state.goodsSpecifications)
        formData.append('goodsUnit',goodsUnitId)
        formData.append('goodsDesc',this.state.goodsDesc)
        formData.append('goodsMarketPrice',this.state.goodsMarketPrice)
        formData.append('referenceCostPrice',this.state.referenceCostPrice)
        formData.append('goodsState',this.state.goodsState)
        formData.append('header',this.state.fileList)

        let config = {
            headers:{
                'Content-Type': 'multipart/form-data',
            }
        }
        axios({
            url:'/api/goods/insertGoodsInfo',
            method:'post',
            data:formData,
            config:config
        }).then(res=>{
            message.success('添加成功')
            this.props.history.push('/homepage/productslist')
        })
    }

    typeSelected(type){
        if(type==='新增商品类型'){
            this.setState({
                visible: true,
            });
        }
        this.setState({
            typeSelectValue:type
        })
    }

    //模态框
    typeOk = e => {
        axios({
            url:'/api/goods/insertGoodsType',
            method: 'post',
            data:{goodsTypeName:this.state.newType}
        }).then(res=>{
            if(res.data.code===200){
                message.success('商品类型添加成功')
                axios({
                    url:'/api/goods/selectGoodsType',
                    method:'post',
                }).then(res=>{
                    let data = res.data.data.filter((item)=>{
                        item.key = item.goodsTypeId
                        delete item.goodsTypeId
                        return item
                    })
                    let allType = {key:1,goodsTypeName:'新增商品类型'}
                    data.unshift(allType)
                    this.setState({
                        goodsType:data
                    })
                })
            }
        })
        this.setState({
            visible: false,
        });
    };

    typeCancel = e => {
        this.setState({
            visible: false,
        });
    };

    changeType=(e)=>{
        this.setState({
            newType:e.target.value
        })
    }
    changeName=(e)=>{
        this.setState({
            goodsName:e.target.value
        })
    }
    changeGuige=(e)=>{
        this.setState({
            goodsSpecifications:e.target.value
        })
    }
    changeUnit=(e)=>{
        this.setState({
            goodsUnit:e.target.value
        })
    }
    changeDetails=(e)=>{
        this.setState({
            goodsDesc:e.target.value
        })
    }
    changeMarketPrice=(e)=>{
        this.setState({
            goodsMarketPrice:e.target.value
        })
    }
    changeCostPrice=(e)=>{
        this.setState({
            referenceCostPrice:e.target.value
        })
    }
    UnitSelected(value){
        this.setState({
            selectUnit:value
        })
    }
    backProList(){
        this.props.history.push('/homepage/productslist')
    }
    render() {
        const { previewVisible, previewImage, fileList, previewTitle } = this.state;
        const uploadButton = (
            <div>
                <PlusOutlined />
                <div className="ant-upload-text">Upload</div>
            </div>
        );
        return (
            <div id='myContent'>
                <Row className='title'>
                    <span>基础信息</span>
                    <Checkbox onChange={this.onChange.bind(this)}>立即上架</Checkbox>
                </Row>
                <Row>
                    <Col id='leftCol'>
                        <span className='xinghao'>*</span>
                        <span>商品名称</span>
                        <Input type='text' onChange={e=>this.changeName(e)} placeholder='长度<64，必填'/>
                    </Col>
                    <Col id='rightCol'>
                        <span className='xinghao'>*</span>
                        <span>商品分类</span>
                        <Dropdown overlay={(<Menu>
                            {this.state.goodsType.map((item,index)=>{
                                return <Menu.Item onClick={()=>this.typeSelected(item.goodsTypeName)} key={index}>{item.goodsTypeName}</Menu.Item>
                            })}
                        </Menu>)}>
                            <Button id='mySelect'>
                                {this.state.typeSelectValue}<DownOutlined />
                            </Button>
                        </Dropdown>
                    </Col>
                </Row>
                <Row>
                    <Col id='leftCol'>
                        <span className='xinghao'>*</span>
                        <span>商品规格</span>
                        <Input type='text' onChange={e=>this.changeGuige(e)} placeholder='长度<64，必填'/>
                    </Col>
                    <Col id='rightCol'>
                        <span className='xinghao'>*</span>
                        <span>计量单位</span>
                        <Dropdown overlay={(<Menu>
                            {this.state.goodsUnitData.map((item,index)=>{
                                return <Menu.Item onClick={()=>this.UnitSelected(item.goodsUnitName)} key={index}>{item.goodsUnitName}</Menu.Item>
                            })}
                        </Menu>)}>
                            <Button id='mySelect'>
                                {this.state.selectUnit}<DownOutlined />
                            </Button>
                        </Dropdown>
                    </Col>
                </Row>
                <Row className='title'>
                    <span>商品图片</span>
                </Row>
                <Row>
                    <Col id='imageCol'>
                        <Upload
                            action="https://www.mocky.io/v2/5cc8019d300000980a055e76"
                            listType="picture-card"
                            fileList={fileList}
                            onPreview={this.handlePreview}
                            onChange={this.handleChange}
                        >
                            {fileList.length >= 8 ? null : uploadButton}
                        </Upload>
                        <Modal
                            visible={previewVisible}
                            title={previewTitle}
                            footer={null}
                            onCancel={this.handleCancel}
                        >
                            <img alt="example" style={{ width: '100%' }} src={previewImage} />
                        </Modal>
                    </Col>
                </Row>
                <Row className='title'>
                    <span>商品描述</span>
                </Row>
                <Row>
                    <Col id='textCol'>
                        <TextArea type='text' onChange={e=>this.changeDetails(e)} rows={7} />
                    </Col>
                </Row>
                <Row className='title'>
                    <span>价格设置</span>
                </Row>
                <Row className='priceInput'>
                    <span>市场价</span>
                    <Input type='text' onChange={e=>this.changeMarketPrice(e)}/>
                </Row>
                <Row className='priceInput'>
                    <span>成本价</span>
                    <Input type='text' onChange={e=>this.changeCostPrice(e)}/>
                    <QuestionCircleOutlined onMouseOver={this.setShow.bind(this)} onMouseOut={this.setHide.bind(this)} id='myCode'/>
                    {this.state.isShow?
                        <div id='tanchuang'>
                        商品首次出入库记录如不是采购入库，将获取
                        此处填写的“参考成本价”作为库存初始成本价；
                        正确填写将有助于更准确核算库存成本及毛利。
                        </div>
                        :<span/>
                    }
                </Row>
                <Row id='bottomRow'>
                    <Col>
                        <Button onClick={this.backProList.bind(this)}>取消</Button>
                        <Button onClick={this.subProducts.bind(this)}>保存</Button>
                    </Col>
                </Row>
                <Modal
                    title="Basic Modal"
                    visible={this.state.visible}
                    onOk={this.typeOk}
                    onCancel={this.typeCancel}
                    cancelText='取消'
                    okText='确定'
                    destroyOnClose={true}
                >
                    请输入新增的类型名称：<Input type='text' onChange={e=>this.changeType(e)}/>
                </Modal>
            </div>
        );
    }
    componentDidMount() {
        axios({
            url:'/api/goods/selectGoodsType',
            method:'post',
        }).then(res=>{
            let data = res.data.data.filter((item)=>{
                item.key = item.goodsTypeId
                delete item.goodsTypeId
                return item
            })
            let allType = {key:1,goodsTypeName:'新增商品类型'}
            data.unshift(allType)
            this.setState({
                goodsType:data
            })
        })
        axios({
            url:'/api/goods/selectGoodsUnit',
            method:'post',
        }).then(res=>{
            let data = res.data.data.filter((item)=>{
                item.key = item.goodsUnitId
                delete item.goodsUnitId
                return item
            })
            this.setState({
                goodsUnitData:data
            })
        })
    }
}

export default withRouter(AddProducts);